﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using FantastPlatform.Framework.IModel;
using FantastPlatform.Framework.Model;
using FantastPlatform.Framework.IService;
using NHibernate;
using FantastPlatform.Framework.Common;
using FantastPlatform.Framework.Exception;
using NHibernate.Criterion;
using FantastPlatform.Framework.Core;

namespace FantastPlatform.Framework.Service
{
    internal class PostService : DataService<IPost, Post>, IPostService
    {
        public override void Delete(int id)
        {
            ITransaction transaction = null;
            ExecuteTransaction((ITransaction tan) =>
            {
                IPost entity = Session.Get<Post>(id) as IPost;
                if (entity != null)
                    Check.Require<InvalidCodeException>(!IsUsing(entity) || CollectionHelper.IsNullOrEmpty<IEmployeePost>(entity.EmployeePosts.Where(c=>c.Enable==true).ToList<IEmployeePost>()), "当前岗位正在被使用不能删除！");
                if (IsUsing(entity))
                {
                    entity.Enable = false;
                    Session.Update(entity);
                }
                else
                {
                    Session.Delete(entity);
                }
            }, transaction);
        }
        public override void Delete(List<int> ids)
        {
            ITransaction transaction = null;
            ExecuteTransaction((ITransaction tan) =>
            {
                foreach (int id in ids)
                {
                    IPost entity = Session.Get<Post>(id) as IPost;
                    if (entity != null)
                        Check.Require<InvalidCodeException>(!IsUsing(entity) || CollectionHelper.IsNullOrEmpty<IEmployeePost>(entity.EmployeePosts.Where(c => c.Enable == true).ToList<IEmployeePost>()), "当前岗位正在被使用不能删除！");
                    if (IsUsing(entity))
                    {
                        entity.Enable = false;
                        Session.Update(entity);
                    }
                    else
                    {
                        Session.Delete(entity);
                    }
                }
            }, transaction);
        }

        public override void Update(IPost entity)
        {
            Check.Require<ArgumentNullException>(entity.Position != null, "职位不能为空！");
            IPost oldPost = Get(entity.Id);
            Check.Require<ArgumentNullException>(oldPost.Organization != null, "当前组织不存在！");
            entity.Organization = oldPost.Organization;
            Session.Evict(oldPost);
            base.Update(entity);
        }
        #region IPostService 成员

        public void AddPost(int organizationId, int positionId, int leaderId, int postResponsibilityId)
        {
            IPost post = new Post();
            IOrganization organization = Session.Get<Organization>(organizationId);
            Check.Require<FrameworkException>(organization != null, "机构为空或不存在！");
            IPosition position = Session.Get<Position>(positionId);
            Check.Require<FrameworkException>(position != null, "职位为空或不存在！");
            IPost leader = null;
            if (leaderId > 0)
            {
                leader = Session.Get<Post>(leaderId);
                Check.Require<ArgumentNullException>(leader != null, "领导岗位不存在！");
            }
            IPostResponsibility postResponsibility = Session.Get<PostResponsibility>(postResponsibilityId);
            Check.Require<FrameworkException>(postResponsibility != null, "分管为空或工作不存在！");
            post.Leader = leader;
            post.PostResponsibility = postResponsibility;
            post.Organization = organization;
            post.Position = position;
            IPost check=Session.CreateCriteria(typeof(Post)).Add(Expression.Eq("Position.Id",positionId))
                .Add(Expression.Eq("Organization.Id",organizationId)).Add(Expression.Eq("Leader.Id",leaderId)).UniqueResult<IPost>();
            Check.Require<ObjectExistedException>(check == null, "当前岗位已经添加！");
            Create(post);
        }

        #endregion

        #region IPostService 成员


        public IList<IEmployee> GetEmployeesByPostId(int postId, IList<Sort> sorts, int pageSize, int page, out int totalCount)
        {

            ICriteria criteria = Session.CreateCriteria(typeof(Employee)).Add(Expression.Eq("Enable",true)).CreateAlias("EmployeePosts", "e")
                .Add(Expression.Eq("e.Post.Id", postId)).Add(Expression.Eq("e.Enable", true));
            ICriteria clone = criteria.Clone() as ICriteria;
            criteria = AddOrderBySorts(criteria, sorts);
            IList<IEmployee> list = criteria.SetFirstResult((page - 1) * pageSize).SetMaxResults(pageSize).List<IEmployee>();
            totalCount = int.Parse(clone.SetProjection(Projections.RowCount()).UniqueResult().ToString());
            return list;
        }

        #endregion
    }
}
